var tools = require('../../lib/system/tools')
var auth = require('../../lib/auth/login')
var constant = require('../../lib/common/constant')
var businessStorage = require('../../lib/common/storage')
var commonConstant = require('../../lib/common/constant')
var pages = require('../../lib/common/pageConstant')

Page({
    /**
     * 页面的初始数据
     */
    data: {
        goodsSum: 1,
        goodsMinusBtnFlag: '1',
        userAddress: {
            name: '收货人姓名',
            address: '收货地址',
            phone: ''
        },
        commonConstant: commonConstant,
        confirmStatus: false,
        orderDetail: {}
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var currentGoods = businessStorage.get('current_pick_goods')
        if (typeof currentGoods['address'] == 'undefined') {
            currentGoods['address'] = ''
        }
        if (typeof currentGoods['contact_phone'] == 'undefined') {
            currentGoods['contact_phone'] = ''
        }
        currentGoods.weight_g = currentGoods.weight_g / 1000
        currentGoods.price = parseFloat(currentGoods.price).toFixed(2) + ''
        currentGoods.order_price = parseFloat(currentGoods.goods_sum * currentGoods.price).toFixed(2)
        currentGoods.express_price = '0.00'
        currentGoods.deposit_price = '0.00'
        currentGoods.discount_price = '0.00'
        currentGoods.settlement_price = parseFloat(currentGoods.order_price) + parseFloat(currentGoods.deposit_price) + parseFloat(currentGoods.express_price) - parseFloat(currentGoods.discount_price)
        currentGoods.settlement_price = currentGoods.settlement_price.toFixed(2)
        this.setData({
            orderDetail: currentGoods,
            goodsSum: currentGoods.goods_sum
        })
        this.settleOrderPrice(currentGoods.goods_sum) 
    },

    confirmOrder: function (e) {
        if (this.data.confirmStatus) {
            return false
        }
        if ((this.data.orderDetail.goods_express_profile_type == '物流') && !this.data.orderDetail.address) {
            wx.showToast({
                title: '请填写收货地址'
            })
            return false
        }
        var that = this
        var currentOrder = that.data.orderDetail
        var confirmOrderParams = {
            open_id: auth.getUserId(),
            quantity: currentOrder.goods_sum,
            payment_method: 'weixin',
            settlement_price: parseFloat(currentOrder.settlement_price),
            logistics_location_id: currentOrder.goods_express_id,
            saler_id: currentOrder.goods_express_owner_id,
            product_distribution_id: currentOrder.goods_express_type,
            product_snapshot: currentOrder,
            user_coupon_id: '',
            address: currentOrder.address,
            contact_phone: auth.getUserPhone()
        }
        auth.checkBind({
            success: function () {
                that.setData({
                    confirmStatus: true
                })
                wx.showLoading({
                    title: '订单提交中'
                })
                tools.requestWithAuth({
                    url: 'profile',
                    feedback: {
                        success: profile => {
                            console.log(profile)
                            confirmOrderParams['contact_phone'] = profile.cell_phone_num
                            tools.requestWithAuth({
                                url: 'order',
                                method: 'POST',
                                data: confirmOrderParams,
                                feedback: {
                                    success: res => {
                                        console.log(res)
                                        if (res) {
                                            that.requestPayment(res, function (res) {
                                                tools.requestWithAuth({
                                                    url: 'pay_order',
                                                    method: 'PUT',
                                                    data: {
                                                        order_id: res.order_id
                                                    },
                                                    feedback: {
                                                        success: dt => {
                                                            wx.switchTab({
                                                                url: pages.homePage
                                                            })
                                                        }
                                                    }
                                                })
                                            })
                                        }
                                        wx.hideLoading()
                                        that.setData({
                                            confirmStatus: false
                                        })
                                    }
                                }
                            })
                        }
                    }
                })
            },
            fail: function () {
                wx.showToast({ title: 'fail' })
            }
        })
    },

    requestPayment: function (signInfo, callback) {
        wx.requestPayment({
            timeStamp: signInfo.timeStamp,
            nonceStr: signInfo.nonceStr,
            package: signInfo.package,
            signType: signInfo.signType,
            paySign: signInfo.paySign,
            success: function (res) {
                console.log(res)
                callback(signInfo)
            },
            fail: function (res) {
                console.log(res)
            }
        })
    },

    addressPick: function (e) {
        wx.chooseAddress({
            success: addRes => {
                if (addRes.errMsg != 'chooseAddress:ok') return false
                var expressAddress = addRes.provinceName + addRes.cityName + addRes.countyName + addRes.detailInfo
                this.setData({
                    'userAddress.name': addRes.userName,
                    'userAddress.address': expressAddress,
                    'userAddress.phone': addRes.telNumber,
                    'orderDetail.address': expressAddress,
                    'orderDetail.contact_phone': addRes.telNumber
                })
                console.log(addRes)
            }
        })
    },
    ajustGoodsSum: function (event) {
        var opeType = event.currentTarget.dataset.ope_type
        var currentGoodsSum = this.data.goodsSum
        switch (opeType) {
            case 'change':
                var newGoodsSum = event.detail.value
                if (!newGoodsSum) return false
                currentGoodsSum = newGoodsSum;
                break;
            case 'add':
                currentGoodsSum += 1
                break;
            case 'minus':
                currentGoodsSum -= 1
                currentGoodsSum = Math.max(currentGoodsSum, 1)
                if (!currentGoodsSum) {
                    this.setData({
                        goodsMinusBtnFlag: '0'
                    })
                }
                break;
        }
        this.settleOrderPrice(currentGoodsSum) 
    },
    settleOrderPrice: function (goodsSum) {
        var that = this
        var currentOrderPrice = parseFloat(this.data.orderDetail.order_price)
        var newOrderPrice = parseFloat(this.data.orderDetail.price * goodsSum)
        tools.requestWithAuth({
            url: 'product_summary',
            data: {
                product_id: that.data.orderDetail.id,
                qty: goodsSum
            },
            feedback: {
                success: function (res) {
                    if (!res.base_price) {
                        return false
                    }
                    var currentPrice = parseFloat(res.base_price).toFixed(2)
                    var cutPrice = parseFloat(res.cut_price).toFixed(2)
                    that.setData({
                        goodsSum: goodsSum,
                        'orderDetail.goods_sum': goodsSum,
                        'orderDetail.order_price': currentPrice,
                        'orderDetail.discount_price': cutPrice,
                        'orderDetail.settlement_price': (currentPrice - cutPrice).toFixed(2)
                    })
                }
            }
        })
    }
})